﻿using fuzhu;
using Microsoft.AspNetCore.Server.IIS.Core;
using SqlSugar;
using System.Data;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.AS;
using ZDEntity;

namespace Yonyou.U8.BO
{
    /// <summary>
    ///不能直接继承，因为调用co时，根据AS_Department类直接转换
    /// </summary>
    public class CustomerVM
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public static string cDatabase = "";

        public AS_Customer entity { get; set; }

        public CustomerVM()
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }

        /// <summary>
        /// 导入U8，新增或修改
        /// </summary>
        /// <returns></returns>
        public RetModel2 Import()
        {

            try
            {
                //检查是否存在这个编码
                bool binv = Exists(entity.cCusCode);
                
                if (!binv)
                {
                    return this.Add();
                }
                else
                {

                    //加上客户发展日期
                     
                    return this.Update();
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }



        }
        public RetModel2 Add()
        {
            try
            {
                string cerr;
                string cid;
                 //末级编码系统自动处理了
                if (CustomerDALCO.AddCustomer(this.entity, xmlConfig, out cerr, out cid))
                {
                    if (!string.IsNullOrWhiteSpace(this.entity.cCusBank) && !string.IsNullOrWhiteSpace(this.entity.cCusAccount))
                    {
                        CustomerBank customerBank = new CustomerBank();
                        customerBank.cCusCode = this.entity.cCusCode;
                        customerBank.cBank = this.entity.cCusBank;
                        customerBank.cBranch = this.entity.cCusBank;
                        customerBank.cAccountNum = this.entity.cCusAccount;
                        customerBank.cAccountName = this.entity.cCusName;
                        customerBank.bDefault = true;
                        using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = conStr,
                            DbType = SqlSugar.DbType.SqlServer,
                            IsAutoCloseConnection = true
                        }))
                        {
                            db.Insertable(customerBank).ExecuteCommand();
                        }

                    }

                   // 更新行业分类，新增不会插入..导入的是名称
                    if (!string.IsNullOrWhiteSpace(this.entity.cTrade))
                    {
                        using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = conStr,
                            DbType = SqlSugar.DbType.SqlServer,
                            IsAutoCloseConnection = true
                        }))
                        {

                             
                                    string sqltrade = $"select cTradeCName From TradeClass where cTradeCCode = '{entity.cTrade}'";
                                    string ctradename = DbHelper.GetDbString(db.Ado.GetScalar(sqltrade));
                                    if (!string.IsNullOrEmpty(ctradename))
                                    { 
                                db.Updateable<Customer>()
                              .SetColumns(x => x.cTrade == ctradename)
                              .Where(x => x.cCusCode == this.entity.cCusCode)
                              .ExecuteCommand();
                            }
                         
                        }
                    }
                    return DBService.ReOKObject("新增完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        ///  变更
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2  Update()
        {
            try
            {
                string cerr;
                string cid; 

                if (CustomerDALCO.ModifyCustomer(this.entity, xmlConfig, out cerr))
                {
                    if (!string.IsNullOrWhiteSpace(this.entity.cCusBank) && !string.IsNullOrWhiteSpace(this.entity.cCusAccount))
                    {
                        CustomerBank customerBank1 = GetCusBank(entity.cCusCode, entity.cCusAccount);
                        if (customerBank1!=null)
                        { 
                            customerBank1.cBank = this.entity.cCusBank;
                            customerBank1.cBranch = this.entity.cCusBank; 
                            customerBank1.cAccountName = this.entity.cCusName;
                            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                            {
                                ConnectionString = conStr,
                                DbType = SqlSugar.DbType.SqlServer,
                                IsAutoCloseConnection = true
                            }))
                            {
                                db.Updateable(customerBank1).ExecuteCommand();
                            }
                        }
                        else
                        {
                            CustomerBank customerBank = new CustomerBank();
                            customerBank.cCusCode = this.entity.cCusCode; 
                            if (string.IsNullOrEmpty(customerBank.cBank))
                            {
                                customerBank.cBank = "01";
                            } 
                            customerBank.cBranch = this.entity.cCusBank;
                            customerBank.cAccountNum = this.entity.cCusAccount;
                            customerBank.cAccountName = this.entity.cCusName;
                          
                            customerBank.bDefault = true;
                            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                            {
                                ConnectionString = conStr,
                                DbType = SqlSugar.DbType.SqlServer,
                                IsAutoCloseConnection = true
                            }))
                            {
                                db.Insertable(customerBank).ExecuteCommand();
                            }
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(this.entity.cTrade))
                    {
                        using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                        {
                            ConnectionString = conStr,
                            DbType = SqlSugar.DbType.SqlServer,
                            IsAutoCloseConnection = true
                        }))
                        {
                            string sqltrade = $"select cTradeCName From TradeClass where cTradeCCode = '{entity.cTrade}'";
                            string ctradename = DbHelper.GetDbString(db.Ado.GetScalar(sqltrade));
                            if (!string.IsNullOrEmpty(ctradename))
                            {
                                db.Updateable<Customer>()
                              .SetColumns(x => x.cTrade == ctradename)
                              .Where(x => x.cCusCode == this.entity.cCusCode)
                              .ExecuteCommand();
                            }
                        }
                    }
                    return DBService.ReOKObject("修改完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
             
        }

        public RetModel2 Delete()
        {
            try
            {
                string cerr;
                string cid;

                if (CustomerDALCO.DelCustomer(entity.cCusCode, xmlConfig, out cerr))
                {
                    return DBService.ReOKObject("删除完成");
                }
                else
                {
                    return DBService.ReErrObject(cerr);
                }

            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        /// <summary>
        /// 检查客户是否存在，返回U8客户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Customer GetByCode()
        {
            if (entity.cCusCode == null)
            {
                return null;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            { 
                
                Customer customer = db.Queryable<Customer>().Where(x => x.cCusCode == entity.cCusCode).First();
                 return customer; 
            } 
        
        }
        /// <summary>
        /// 检查客户是否存在
        /// </summary>
        /// <param name="cCusCode"></param>
        /// <returns></returns>
        public bool Exists(string cCusCode)
        {
           
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {


              var cus = db.Queryable<Customer>().Where(x => x.cCusCode == cCusCode).First();
                if (cus==null)
                {
                    return false;
                }
                else
                {
                    //如果客户档案更新存在，加上发展日期
                    if (this.entity!=null)
                    {
                       
                        this.entity.dCusDevDate = DbHelper.GetDbString(DbHelper.GetDbDate(cus.dCusDevDate));
                    }
                    
                    return true;
                }
             


             
            }
        }

        /// <summary>
        /// 检查客户银行是否存在
        /// </summary>
        /// <param name="cCusCode"></param>
        /// <returns></returns>
        public CustomerBank GetCusBank(string cCusCode,string cCusAccount)
        {

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = CanShu.conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                
               CustomerBank customerBank = db.Queryable<CustomerBank>().Where(x => x.cCusCode == cCusCode && x.cAccountNum == cCusAccount).First();

                return customerBank;
            }
        }
        public void MergeEntity()
        {
            //取默认值合并
            entity = ASService.MergeEntity<AS_Customer>(entity, CanShu.cusModel);
        }
    }
}
